<template>
  <el-dialog title="选择地址" :visible.sync="visible" width="750px" @closed="close">
    <div class="content">
      <el-select v-model="choose" placeholder="" style="width: 20%;" @change="chooseChange">
        <el-option
          v-for="item in chooseMap"
          :key="item.value"
          :label="item.desc"
          :value="item.value"
        />
      </el-select>
      <el-select v-show="choose === 1" v-model="addressType" placeholder="请选择地址" style="width: 70%;">
        <el-option
          v-for="item in addressList"
          :key="item.value"
          :label="item.desc"
          :value="item.value"
        />
      </el-select>
      <div v-if="choose === 1 && addressType === 1" class="choose-tip">当前地址为配送员提交位置</div>
      <div v-if="choose === 1 && addressType === 2" class="choose-tip">当前地址为用户订单地址</div>
      <el-autocomplete
        v-show="choose === 2"
        ref="suggestionInput"
        v-model="temp.address"
        v-scrollLoad="getLoad"
        :maxlength="50"
        :debounce="300"
        popper-class="address-autocomplete"
        :fetch-suggestions="queryAddressSearch"
        placeholder="请输入联系地址"
        :trigger-on-focus="false"
        @select="handleSelect"
      >
        <template slot-scope="{ item }">
          <div class="name">{{ item.value }}</div>
          <span class="addr">{{ item.address }}</span>
        </template>
      </el-autocomplete>
      <el-button v-show="choose === 2" type="primary" icon="el-icon-location-information" @click="location" />
      <div v-show="choose === 2" class="row">
        <span>所在区域：</span>
        <el-select
          v-model="temp.province"
          placeholder="请选择省"
          style="width: 20%;"
          @change="provinceChange"
        >
          <el-option
            v-for="item in provinceList"
            :key="item.value"
            :label="item.areaName"
            :value="item.areaCode"
          />
        </el-select>
        <el-select
          v-model="temp.city"
          placeholder="请选择市"
          style="width: 20%;"
          @change="cityChange"
        >
          <el-option
            v-for="item in cityList"
            :key="item.value"
            :label="item.areaName"
            :value="item.areaCode"
          />
        </el-select>
        <el-select
          v-model="temp.area"
          placeholder="请选择区"
          style="width: 20%;"
          @change="areaChange"
        >
          <el-option
            v-for="item in areaList"
            :key="item.value"
            :label="item.areaName"
            :value="item.areaCode"
          />
        </el-select>
        <el-select v-model="temp.street" placeholder="请选择街道" style="width: 20%;" @change="streetChange">
          <el-option
            v-for="item in streetList"
            :key="item.value"
            :label="item.areaName"
            :value="item.areaCode"
          />
        </el-select>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关 闭</el-button>
      <el-button type="primary" @click="save">保 存</el-button>
    </span>
    <location ref="location" />
  </el-dialog>
</template>

<script>
  import { selectAreaCode, changeAddress, queryRecordByAppealCode } from '@/api'
  import { getLocalSearch } from '@/utils/BMap'
  import { formatColumnMap } from '@/utils'
  import location from './location.vue'
  export default {
    name: 'chooseAddress',
    components: { location },
    directives: {
      scrollLoad: {
        bind(el, binding, vnode) {
          const wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
          const listDom = el.querySelector('.el-autocomplete-suggestion__list')
          wrapDom.addEventListener(
            'scroll',
            e => {
              const condition =
                listDom.offsetHeight -
                wrapDom.offsetHeight +
                37 -
                0.3 -
                wrapDom.scrollTop
              if (condition < 0 && !vnode.context.loading) {
                // 滚动到底部则执行滚动方法load，binding.value就是v-scrollLoad绑定的值，加()表示执行绑定的方法
                binding.value()
              }
            },
            false
          )
        }
      }
    },
    data() {
      return {
        visible: false,
        choose: 1,
        chooseMap: [
          {
            desc: '选择地址',
            value: 1
          },
          {
            desc: '编辑地址',
            value: 2
          }
        ],
        addressList: [],
        slectAddress: {},
        addressInfo: {
          page_num: 0,
          page_size: 10
        },
        suggestionCb: undefined,
        suggestionList: [],
        temp: {
          latitude: '',
          longitude: '',
          province: '',
          provinceName: '',
          city: '',
          cityName: '',
          countryName: '',
          area: '',
          street: '',
          streetName: '',
          address: ''
        },
        addressType: '',
        provinceList: [],
        cityList: [],
        areaList: [],
        streetList: []
      }
    },
    methods: {
      async open(val) {
        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
          this.clearData()
          this.choose = 1
          this.row = val
          this.getProvinceData()
          this.getData()
        })
      },
      async getData() {
        const res = await queryRecordByAppealCode({ recordId: this.row.recordId })
        this.newAddress = res.data.newAddress
        this.addressList = [
          {
            desc: res.data.newAddress,
            value: 1
          },
          {
            desc: res.data.oldAddress,
            value: 2
          }
        ]
        this.temp.address = this.addressList[0].desc
        this.cityList = await this.getAreaData(this.row.provinceCode)
        this.areaList = await this.getAreaData(this.row.cityCode)
        this.streetList = await this.getAreaData(this.row.countryCode)
        this.temp.province = this.row.provinceCode
        this.temp.city = this.row.cityCode
        this.temp.area = this.row.countryCode
        this.temp.street = this.row.streetCode
        this.temp.provinceName = this.row.provinceName
        this.temp.cityName = this.row.cityName
        this.temp.countryName = this.row.countryName
        this.temp.streetName = this.row.streetName
        this.temp.latitude = this.row.latitude
        this.temp.longitude = this.row.longitude
      },
      clearData() {
        this.temp = {
          latitude: '',
          longitude: '',
          province: '',
          provinceName: '',
          city: '',
          cityName: '',
          countryName: '',
          area: '',
          street: '',
          streetName: '',
          address: ''
        }
        this.addressType = ''
      },
      async chooseChange(val) {
      },
      // 省市区
      async getAreaData(value) {
        const res = await selectAreaCode({ areaCode: value || 0 })
        return res.data
      },
      async getProvinceData() {
        this.provinceList = await this.getAreaData(0)
      },
      async provinceChange() {
        this.temp.provinceName = this.getAreaName(this.temp.province, this.provinceList)
        this.temp.city = ''
        this.temp.area = ''
        this.temp.street = ''
        this.cityList = await this.getAreaData(this.temp.province)
      },
      async cityChange() {
        this.temp.cityName = this.getAreaName(this.temp.city, this.cityList)
        this.temp.area = ''
        this.temp.street = ''
        this.areaList = await this.getAreaData(this.temp.city)
      },
      async areaChange() {
        this.temp.countryName = this.getAreaName(this.temp.area, this.areaList)
        this.temp.street = ''
        this.streetList = await this.getAreaData(this.temp.area)
      },
      async streetChange() {
        this.temp.streetName = this.getAreaName(this.temp.street, this.streetList)
      },
      getAreaName(code, list) {
        const codeItem = list.find(item => item.areaCode === code)
        if (codeItem && codeItem.areaName) return codeItem.areaName
        else return ''
      },
      // 输入建议
      async getAddressSuggestionList(cb) {
        const params = {
          page_num: this.addressInfo.page_num,
          page_size: this.addressInfo.page_size,
          queryString: this.temp.address,
          city: this.temp.cityName
        }
        const res = await getLocalSearch(params)
        if (res && res.results && res.results.length > 0) {
          let list = []
          list = res.results.map(item => ({
            value: item.name || '',
            location: item.location,
            address: item.address || '',
            adcode: item.adcode || '',
            province: item.province || '',
            city: item.city || '',
            area: item.area || ''
          }))
          if (cb) {
            this.suggestionList = list
            cb(this.suggestionList)
          } else {
            this.$nextTick(() => {
              if (params.page_num > 0) {
                this.suggestionList = this.suggestionList.concat(list)
                this.$refs.suggestionInput.suggestions = this.suggestionList
              }
            })
          }
        } else {
          if (cb) {
            this.$message.error('未匹配到正确地址信息，请重新输入详细地址')
            cb([])
          }
        }
      },
      getLoad() {
        console.log('i am load')
        this.addressInfo.page_num++
        this.$refs.suggestionInput.fetchSuggestions()
      },
      // 地址模糊匹配
      async handleSelect(item) {
        console.log(item)
        const latAndLon = item.location
        if (latAndLon && latAndLon.lat && latAndLon.lng) {
          this.temp.latitude = latAndLon.lat
          this.temp.longitude = latAndLon.lng
          this.slectAddress = {
            address: this.temp.address
          }
          this.temp.provinceName = item.province
          this.temp.cityName = item.city
          this.temp.countryName = item.area
          this.temp.streetName = ''
          this.temp.street = ''
          this.temp.province = formatColumnMap(this.provinceList, 'areaName', this.temp.provinceName, 'areaCode')
          this.cityList = await this.getAreaData(this.temp.province)
          this.temp.city = formatColumnMap(this.cityList, 'areaName', this.temp.cityName, 'areaCode')
          this.areaList = await this.getAreaData(this.temp.city)
          this.temp.area = formatColumnMap(this.areaList, 'areaName', this.temp.countryName, 'areaCode')
          this.streetList = await this.getAreaData(this.temp.area)
        }
      },
      async queryAddressSearch(queryString, cb) {
        if (queryString !== this.slectAddress.address) {
          this.addressInfo.page_num = 0
        }
        this.getAddressSuggestionList(cb)
      },
      // 定位
      async location() {
        console.log(this.temp)
        const res = await this.$refs.location.open(this.temp)
        console.log(res)
        // 处理详细地址
        this.temp.latitude = res.point.lat
        this.temp.longitude = res.point.lng
        this.temp.address = res.address
        this.temp.provinceName = res.province
        this.temp.cityName = res.city
        this.temp.countryName = res.district
        this.temp.streetName = res.streetName || ''
        this.temp.street = res.street || ''
        this.temp.province = formatColumnMap(this.provinceList, 'areaName', this.temp.provinceName, 'areaCode')
        this.cityList = await this.getAreaData(this.temp.province)
        this.temp.city = formatColumnMap(this.cityList, 'areaName', this.temp.cityName, 'areaCode')
        this.areaList = await this.getAreaData(this.temp.city)
        this.temp.area = formatColumnMap(this.areaList, 'areaName', this.temp.countryName, 'areaCode')
        this.streetList = await this.getAreaData(this.temp.area)
      },
      close() {
        this.visible = false
      },
      save() {
        if (this.choose === 1) {
          if (!this.addressType) {
            this.$message.warning('地址不能为空')
            return
          }
          const newAddress = this.addressList[this.addressType - 1].desc
          console.log(newAddress)
          const param = {
            appealCode: this.row.appealCode,
            newAddress: newAddress
          }
          changeAddress(param).then(res => {
            if (res.data) {
              this.$message.success('保存成功')
              this.visible = false
              this.$emit('refresh')
            }
          })
        }
        if (this.choose === 2) {
          if (!this.temp.address) {
            this.$message.warning('地址不能为空')
            return
          }
          if (!this.temp.province) {
            this.$message.warning('请选择省')
            return
          }
          if (!this.temp.city) {
            this.$message.warning('请选择城市')
            return
          }
          if (!this.temp.area) {
            this.$message.warning('请选择区')
            return
          }
          if (!this.temp.street) {
            this.$message.warning('请选择街道')
            return
          }
          // const newAddress = this.temp.provinceName + this.temp.cityName + this.temp.countryName + this.temp.streetName + this.temp.address
          const param = {
            appealCode: this.row.appealCode,
            newAddress: this.temp.address,
            provinceName: this.temp.provinceName,
            provinceCode: this.temp.province,
            cityName: this.temp.cityName,
            cityCode: this.temp.city,
            countryName: this.temp.countryName,
            countryCode: this.temp.area,
            streetName: this.temp.streetName,
            streetCode: this.temp.street,
            longitude: this.temp.longitude,
            latitude: this.temp.latitude
          }
          if (this.row.url && (this.temp.address !== this.newAddress || this.temp.province !== this.row.provinceCode || this.temp.city !== this.row.cityCode || this.temp.area !== this.row.countryCode || this.temp.street !== this.row.streetCode || this.temp.longitude !== this.row.longitude || this.temp.latitude !== this.row.latitude)) {
            param.isAddressChange = 1
          } else {
            param.isAddressChange = 0
          }
          changeAddress(param).then(res => {
            if (res.data) {
              this.$message.success('保存成功')
              this.visible = false
              this.$emit('refresh')
            }
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    width: 100%;
    .el-autocomplete {
      width: 60%;
    }
    .row {
      margin-top: 20px;
    }
    .choose-tip {
      margin-top: 10px;
      margin-left: 140px;
      color: #F56C6C;
    }
  }
</style>
